import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams

rcParams['font.family'] = "Times New Roman"
rcParams['font.size'] = 15
rcParams['font.weight'] = 'normal'

'''
flow completion time(FCT)
Average FCTs
99th %-tile FCTs

(0,100KB]: Avg 
(0,100KB]: 99th Percentile 
(100KB,10MB]: Avg
(10MB,++): Avg
'''


def get_overall_fct(fct_list):
    """
    :param: overall fct_list
    :return: sum_fct, average_fct
    """
    overall_sum_fct = 0
    for x in fct_list:
        overall_sum_fct += x
    overall_avg_fct = overall_sum_fct / len(fct_list)
    return overall_sum_fct, overall_avg_fct


def get_tail99_fct(tail99_fct_list):
    """
    :param: 99th %-tile fct_list
    :return: 99th %-tile sum and average FCT
    """
    tail99_sum_fct = 0
    for x in tail99_fct_list:
        tail99_sum_fct += x
    tail99_avg_fct = tail99_sum_fct / len(tail99_fct_list)
    return tail99_sum_fct, tail99_avg_fct


if __name__ == '__main__':

    # topology
    numToRs = 16
    numHosts = 10
    numLinks = 6
    numSLinks = 2

    # workloads
    flowsDir = "case1/"
    load = 0.6
    time = 0.4
    randomSeed = 1
    workloadCDFs = ["VL2"]
    workloadTypes = ["random"]

    # scheduler
    schedulers = ['Detour', 'OvS', 'Jelly', 'OSA']  # ,  "OvS"
    interval = 0.4e-1  # Periodicity get the traffic matrix (Seconds)
    adjust_delay = 10.0e-3  # Circuit switching time (Seconds) 10ms
    sample_enable = True  #
    sample_interval = 1.0e-4  # sample network throughput

    iteration_a = 0
    iteration_b = 1

    osa_fct = []
    ovs_fct = []
    jelly_fct = []
    detour_fct = []

    fctDicts = {}
    tail99_fctDicts = {}

    for round_i in range(iteration_a, iteration_b):
        for workloadCDF in workloadCDFs:
            for workloadType in workloadTypes:
                for scheduler in schedulers:
                    flowsFileName = "%s_%sToR_%sHosts_%sLinks_%sload_%stime_%s_%s_%s.txt" \
                                    % (scheduler, numToRs, numHosts, numLinks, load, time, workloadCDF, workloadType,
                                       round_i)
                    # print (flowsFileName)
                    with open(flowsFileName, 'r') as f:
                        for line in f.readlines():
                            split = line.split()
                            if len(split) == 12:
                                if scheduler == "Detour":
                                    if "Detour" not in fctDicts:
                                        fctDicts["Detour"] = [float(split[5]) * 1000]
                                    else:
                                        fctDicts["Detour"].append(float(split[5]) * 1000)
                                elif scheduler == "OvS":
                                    if "OvS" not in fctDicts:
                                        fctDicts["OvS"] = [float(split[5]) * 1000]
                                    else:
                                        fctDicts["OvS"].append(float(split[5]) * 1000)
                                elif scheduler == "OSA":
                                    if "OSA" not in fctDicts:
                                        fctDicts["OSA"] = [float(split[5]) * 1000]
                                    else:
                                        fctDicts["OSA"].append(float(split[5]) * 1000)
                                elif scheduler == "Jelly":
                                    if "Jelly" not in fctDicts:
                                        fctDicts["Jelly"] = [float(split[5]) * 1000]
                                    else:
                                        fctDicts["Jelly"].append(float(split[5]) * 1000)
                            else:
                                print ("%s \t %s \t %s" % (scheduler, split[0], split[1]))

    # -------------overall fct-------------
    for scheduler in fctDicts:
        fctDicts[scheduler].sort()
    # -------------99tail fct-------------
    for scheduler in fctDicts:
        fct = fctDicts[scheduler]
        tail99_fctDicts[scheduler] = fct[-len(fct) / 100 + 1:]

    # plot
    fs = 14
    ls = 1
    fig = plt.figure(figsize=(5.8, 3.5))
    ax = plt.axes()

    colors = {'OSA': 'r', 'OvS': 'b', 'Jelly': 'y', 'Detour': 'g'}
    legends = {'OSA': 0, 'OvS': 0, 'Jelly': 0, 'Detour': 0}
    for scheduler in fctDicts:
        cdfx = fctDicts[scheduler]
        cdfy = np.linspace(1 / len(fctDicts[scheduler]), 1.0, len(fctDicts[scheduler]))
        legends[scheduler], = plt.semilogx(cdfx, cdfy, colors[scheduler], linewidth=ls)

    plt.xlim(0.0, 10000)
    plt.xlabel('FCT(ms)', fontsize=fs)
    plt.ylabel('CDF', fontsize=fs)
    plt.legend((legends['Detour'], legends['OvS'], legends['Jelly']), ('Detour', 'OvS', 'Jellyfish'), loc=4, fontsize=fs)
    plt.subplots_adjust(bottom=0.18, top=0.9, left=0.12, right=0.95)
    ax.yaxis.grid(zorder=0, ls='--')
    plt.show()
